import { createSlice } from "@reduxjs/toolkit";
import type { RootState } from "./index";

// 这里是该模块的state的类型
interface userState {
  token: string;
}

const initialState: userState = {
  // token的类型是string，localStorage.getItem的类型是 string | null, 所以赋值会有问题
  token: localStorage.getItem("token") as string,
};

export const userSlice = createSlice({
  name: "user",
  initialState: initialState,
  reducers: {
    // 保存token
    setToken(state, action) {
      state.token = action.payload;
    },
  },
});

// 导出的方法是用于生成 { type: "add", payload: "" } 的对象
export const { setToken } = userSlice.actions;

// 在index里面取回类型，将token点出来
export const selectToken = (state: RootState) => state.user.token;

export default userSlice.reducer;
